<template>
  <el-card class="box-card AddNewsContainer">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="newsRules"
        label-width="120px"
        class="demo-ruleForm"
        size="default"
        status-icon
    >
      <!--      文章标题-->
      <el-form-item label="文章标题" prop="validateTitle">
        <el-input v-model="formData.title"/>
      </el-form-item>
      <!--      文章类别-->
      <el-form-item label="文章类别" prop="validateType">
        <el-select v-model="formData.category" placeholder="选择文章类别">
          <el-option v-for="item in articleType" :label="item.categoryName" :value="item.cid">
          </el-option>
        </el-select>
      </el-form-item>
      <!--      文章内容-->
      <el-form-item  label="文章内容" prop="validateArticle">
        <el-input :rows="15" class="textarea" v-model="formData.articleContent" type="textarea"/>
      </el-form-item>
      <!--      文章按钮-->
      <el-form-item>
        <el-button type="primary" @click="insert()">
          新建
        </el-button>
        <el-button @click="back()">
          取消
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>



import router from "../../routers/router.js";

const formRef = ref()

// 校验规则
import {onMounted, ref} from "vue";
import {getCategoryTypeApi} from "../../api/articleCategoryApi.js";
import {useRoute} from "vue-router";
import {insertArticle} from "../../api/articleApi.js";
const route = useRoute()


const validateType = (rule, value, callback) => {
  if (value.length) {
    callback()
  } else {
    callback(new Error('文章标题是必须的'))
  }
}
// 校验规则
const validateArticle = (rule, value, callback) => {
  if (value.length) {
    callback()
  } else {
    callback(new Error('文章内容是必须的'))
  }
}
// 校验规则
const validateTitle = (rule, value, callback) => {
  if (value.length) {
    callback()
  } else {
    callback(new Error('文章类别是必须的'))
  }
}
// 校验规则
const newsRules = {
  title: [{required: true, trigger: 'blur', validator: validateTitle}],
  article: [{required: true, trigger: 'blur', validator: validateArticle}],
  type: [{required: true, validator: validateType}],
}
const formData = ref({
  author: route.query.account,
  title: "",   // 文章标题
  articleContent: "", // 文章内容
  category: ""     // 文章类别
})
//初始化文章类别数据
const articleType = ref([{
  cid:null,
  categoryName:''
}])
async function initArticleType() {
  let {data} = await getCategoryTypeApi()
  articleType.value = data.data.ArticleType
}
onMounted(()=>{
  initArticleType()
})
function insert() {
  insertArticle(formData.value)
  router.push("/home")
}

function back() {
  router.push("/home")
}

</script>

<style scoped>
.AddNewsContainer {
  width: 700px;
  margin-left: 700px;
  margin-top: 200px;
  //margin: 150px auto;
}

</style>